<template>
  <div class="mouse-position">
    <p>mouse position</p>
    <div>鼠标位置：{{ x }}-{{ y }} </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue';

// 合成函数返回应该和setup一样是一个ref组成的普通对象
function useMousePosition() {
  // 如果这里用 reactive，则最后return的时候要 toRefs，方便函数使用的地方可以解构（reactive解构会丢失响应式）
  const x = ref(0)
  const y = ref(0)

  function update(e:MouseEvent) {
    x.value = e.pageX
    y.value = e.pageY
  }

  onMounted(() => {
    console.log('onMounted')
    window.addEventListener('mousemove', update)
  })

  onUnmounted(() => {
    console.log('onUnmounted')
    window.removeEventListener('mousemove', update)
  })

  return {
    x,
    y
  }
}


export default defineComponent({
  name: 'MousePosition',
  props: {
  },
  setup() {
    const { x, y } = useMousePosition()

    return {
      x, 
      y
    }

  }
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
